package com.newenergy.wisehome.gateway.manager;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.newenergy.wisehome.common.helper.StorageHelper;
import com.newenergy.wisehome.common.manager.MyThreadManager;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.BaseApp;
import com.newenergy.wisehome.data.bean.BLDeviceInfo;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.BLDeviceInfoDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.gateway.common.BLCommonUtils;
import com.newenergy.wisehome.gateway.common.BLModelUtil;
import com.newenergy.wisehome.gateway.listener.BLFamilyListener;
import com.newenergy.wisehome.ui.widget.LoaddingDialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.com.broadlink.account.BLAccount;
import cn.com.broadlink.base.BLAppSdkErrCode;
import cn.com.broadlink.base.BLBaseResult;
import cn.com.broadlink.base.BLLoginResult;
import cn.com.broadlink.family.BLFamily;
import cn.com.broadlink.family.params.BLFamilyAllInfo;
import cn.com.broadlink.family.params.BLFamilyBaseInfo;
import cn.com.broadlink.family.params.BLFamilyDeviceInfo;
import cn.com.broadlink.family.params.BLFamilyInfo;
import cn.com.broadlink.family.params.BLFamilyModuleInfo;
import cn.com.broadlink.family.params.BLFamilyRoomInfo;
import cn.com.broadlink.family.result.BLAllFamilyInfoResult;
import cn.com.broadlink.family.result.BLFamilyBaseInfoListResult;
import cn.com.broadlink.family.result.BLFamilyInfoResult;
import cn.com.broadlink.family.result.BLModuleControlResult;
import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.data.controller.BLDNADevice;

public class BLLocalFamilyManager {
    public static final String TAG = "LFX";

    private BLFamilyListener mBLFamilyListener;
    public Context mContext;
    public boolean isLogin;
    public String mDid;
    public boolean isUpdateBLDeviceFamilyId = true;
    public final HashMap<String, BLDNADevice> LOCAL_DEVICES_MAP = new HashMap<>();
    public final HashMap<String, BLDNADevice> SDK_DEVICES_MAP = new HashMap<>();

    private static BLLocalFamilyManager sharedInstance = null;
    public BLDNADevice mLocalDnaDevice;
    public DeviceCategory mDeviceCategory;
    public boolean isAddBLFamilyDevices = true;

    public Family mFamily;
    public String mFamilyId;
    public String mBLFamilyId;
    public BLFamilyRoomInfo mRoomInfo;
    private String currentFamilyVersion;
    private BLFamilyAllInfo currentFamilyAllInfo;
    private Toast mToast;
    private BLFamilyDeviceInfo mDeviceInfo;
    public List<DeviceCategory> mFamilyCategorys;
    private BLFamilyInfo mBLFamilyInfo;
    //0-之创建BL家庭    3-先删除旧的家庭，再创建新的家庭
    private int createBLFamilyType = 0;
    private List<BLFamilyBaseInfo> mAllBLFamilyInfoList;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private Dialog mLoadingDialog;
    private Activity mActivity;

    public void setCurrFamily(Family family) {
        if (family == null) {
            return;
        }
        Log.i(TAG, "setCurrFamily: family = " + family.toString());
        mFamily = family;
        mFamilyId = family.getFamilyId();
        setBLFamilyId(family.getBlFamilyId());
        addFamilyDeviceToSdk(mFamilyId);
        getFamilyLocalDevice(mFamilyId);
        //更新分享家庭的网关信息
        if (family.getType() != 1 && !TextUtils.isEmpty(family.getBlFamilyId())) {
            updateShareFamilyBLInfo(family);
        }
    }

    public void getFamilyLocalDevice(String familyId) {
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(mContext);
        List<BLDeviceInfo> familyBLDeviceInfos = deviceInfoDao.getFamilyBLDeviceInfos(familyId);
        if (familyBLDeviceInfos != null || familyBLDeviceInfos.size() > 0) {
            for (BLDeviceInfo deviceInfo : familyBLDeviceInfos) {
                Log.i(TAG, "familyBLDeviceInfos: deviceInfo =  " + deviceInfo.toString());
            }
        }
        List<BLDeviceInfo> deviceInfos = deviceInfoDao.getFamilyBLDeviceInfos(familyId, 0);
        if (deviceInfos != null && deviceInfos.size() > 0) {
            BLDeviceInfo blDeviceInfo = deviceInfos.get(0);
            mLocalDnaDevice = blDeviceInfo.cloneBLDNADevice();
        }
    }

    public void saveBLLocalDevice(BLDeviceInfo deviceInfo) {
    }

    public void updateShareFamilysBLInfo() {
        if (!checkAppState()) {
            return;
        }
        FamilyDao familyDao = new FamilyDao(mContext);
        List<Family> families = familyDao.getFamiliesByType(0);
        if (families == null || families.size() < 1) {
            return;
        }
        List<Family> shareBLFamilies = new ArrayList<>();
        for (Family family : families) {
            if (!TextUtils.isEmpty(family.getBlFamilyId())) {
                shareBLFamilies.add(family);
            }
        }
        updateShareFamilysBLInfo(shareBLFamilies);
    }

    public void updateShareFamilysBLInfo(List<Family> families) {
        Log.i(TAG, "updateBLShareFamilys:isMainThread =  " + isMainThread());
        if (families == null || families.size() < 1) {
            return;
        }
        if (isMainThread()) {
            MyThreadManager.getInstance().doTask(() -> {
                for (Family family : families) {
                    updateBLShareFamilyTask(family);
                }
            });
        } else {
            for (Family family : families) {
                updateBLShareFamilyTask(family);
            }
        }
    }

    /*** 判断当前线程是否是在主线程*/
    public boolean isMainThread() {
        return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
    }

    public void updateShareFamilyBLInfo(Family family) {
        if (!checkAppState()) {
            return;
        }
        if (!TextUtils.isEmpty(family.getBlFamilyId())) {
            MyThreadManager.getInstance().doTask(() -> {
                updateBLShareFamilyTask(family);
            });
        }
    }

    /*** 更新分享家庭的网关信息的任务*/
    public void updateBLShareFamilyTask(Family family) {
        String currFamilyId = StorageHelper.getCurrFamilyId();
        boolean isCurrFamily = family.getFamilyId().equals(currFamilyId);
        Log.i(TAG, "updateBLShareFamilyTask:是否是当前家庭 = " + isCurrFamily);
        String blFamilyId = family.getBlFamilyId();
        String familyId = family.getFamilyId();
        DeviceCategoryDao categoryDao = new DeviceCategoryDao(mContext);
        List<DeviceCategory> lightings = categoryDao.getFamilyLighting(familyId);
        Log.i(TAG, "更新分享的家庭的网关信息: family = " + family.toString());
        BLFamilyAllInfo familyAllInfo = queryBLFamilyAllInfoTask(blFamilyId);
        if (familyAllInfo == null || familyAllInfo.getFamilyInfo() == null) {
            //网关家庭已被删除
            new BLDeviceInfoDao(mContext).deleteFamilyBLDeviceInfos(familyId);
            family.setBlType(0);
            family.setBlFamilyId("");
            new FamilyDao(mContext).updateFamily(family);
            if (lightings == null || lightings.size() < 1) {
                return;
            }
            for (DeviceCategory lighting : lightings) {
                lighting.setBlDid("");
                categoryDao.updateDeviceCategory(lighting);
            }
            return;
        }
        if (lightings == null || lightings.size() < 1) {
            return;
        }
        List<BLFamilyDeviceInfo> familyDeviceInfos = familyAllInfo.getDeviceInfos();
        if (familyDeviceInfos == null || familyDeviceInfos.size() < 1) {
            return;
        }

        family.setBlType(1);
        new FamilyDao(mContext).updateFamily(family);
        HashMap<String, BLFamilyDeviceInfo> familyDeviceMap = new HashMap<>();
        for (BLFamilyDeviceInfo deviceInfo : familyDeviceInfos) {
            String did = deviceInfo.getDid();
            String groupId = did.substring(did.length() - 2);
            familyDeviceMap.put(groupId, deviceInfo);
            if (groupId.equals("00")) {
                BLDeviceInfo blAllDeviceInfo = BLModelUtil.toBLDeviceInfo(deviceInfo);
                addSdkDevice(blAllDeviceInfo);
                blAllDeviceInfo.setFamilyId(familyId);
                updateBLDeviceInfo(blAllDeviceInfo);
                if (isCurrFamily) {
                    AppManager.getInstance(mContext).mBLAllDeviceInfo = blAllDeviceInfo;
                }
            }
        }
        for (DeviceCategory lighting : lightings) {
            String groupId = lighting.getGroupId();
            BLFamilyDeviceInfo deviceInfo = familyDeviceMap.get(groupId);
            if (deviceInfo != null) {
                BLDNADevice bldnaDevice = BLModelUtil.toDNADevice(deviceInfo);
                addSdkDevice(bldnaDevice);
                BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(deviceInfo);
                blDeviceInfo.setFamilyId(familyId);
                updateBLDeviceInfo(blDeviceInfo);
                String did = blDeviceInfo.getDid();
                lighting.setBlDid(did);
                categoryDao.updateDeviceCategory(lighting);
                Log.i(TAG, "updateBLShareFamilyTask: deviceInfo= " + deviceInfo.toDictionary());
                Log.i(TAG, "updateBLShareFamilyTask: lighting= " + lighting.toString());
            }
        }
    }

    /*** 显示加载对话框*/
    public void showLoading(final String msg) {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
        if (isMainThread()) {
            mLoadingDialog = LoaddingDialogUtils.createLoadingDialog(mActivity, msg);
            return;
        }
        mHandler.post(() -> {
            mLoadingDialog = LoaddingDialogUtils.createLoadingDialog(mActivity, msg);
        });
    }

    /*** 显示加载对话框*/
    public void dismissLoading() {
        if (mLoadingDialog == null || !mLoadingDialog.isShowing()) {
            return;
        }
        if (isMainThread()) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
            return;
        }
        mHandler.post(() -> {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        });
    }

    /*** 添加当前家庭的全部设备到SDK */
    public void addFamilyDeviceToSdk(String familyId) {
        mFamilyId = familyId;
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(mContext);

        List<BLDeviceInfo> allBLDeviceInfo = deviceInfoDao.getAllBLDeviceInfo();
        for (BLDeviceInfo blDeviceInfo : allBLDeviceInfo) {
            Log.i(TAG, "allBLDeviceInfo:deviceInfo = " + blDeviceInfo.toString());

        }
        List<BLDeviceInfo> deviceInfos = deviceInfoDao.getFamilyBLDeviceInfos(familyId);
        if (deviceInfos == null || deviceInfos.size() < 1) {
            Log.i(TAG, "没有设备，addFamilyDeviceToSdk:familyId = " + familyId);
            return;
        }
        for (BLDeviceInfo deviceInfo : deviceInfos) {
            String did = deviceInfo.getDid();
            Log.i(TAG, "addFamilyDeviceToSdk:deviceInfo = " + deviceInfo.toString());
            if (did.endsWith("00")) {
                AppManager.getInstance(mContext).mBLAllDeviceInfo = deviceInfo;
            }
            BLDNADevice bldnaDevice = deviceInfo.cloneBLDNADevice();
            addSdkDevice(bldnaDevice);
        }
    }

    //保存BL设备信息
    public void updateBLDeviceInfo(BLDeviceInfo deviceInfo) {
        Log.i(TAG, "updateBLDeviceInfo: deviceInfo = " + deviceInfo.toString());
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(mContext);
        deviceInfoDao.addOrUpdate(deviceInfo);
    }

    public void addSdkDevice(BLDeviceInfo blDeviceInfo) {
        BLDNADevice dnaDevice = BLModelUtil.toDNADevice(blDeviceInfo);
        addSdkDevice(dnaDevice);
    }

    public void addSdkDevice(BLDNADevice device) {
        BLLet.Controller.addDevice(device);
        SDK_DEVICES_MAP.put(device.getDid(), device);
    }

    public void addLocalDevice(BLDNADevice device) {
        mLocalDnaDevice = device;
        addSdkDevice(device);
        LOCAL_DEVICES_MAP.put(device.getDid(), device);
    }

    public static BLLocalFamilyManager getInstance() {
        return Holder.INSTANCE;
    }

    public void delBLDevice(Family family, DeviceCategory category) {
        if (family == null || TextUtils.isEmpty(family.getBlFamilyId())) {
            return;
        }
        if (category == null || TextUtils.isEmpty(category.getBlDid())) {
            return;
        }
        if (!checkAppState()) {
            return;
        }
        String blDid = category.getBlDid();
        String blFamilyId = family.getBlFamilyId();
        MyThreadManager.getInstance().doTask(() -> {
            BLFamilyAllInfo blFamilyAllInfo = queryBLFamilyAllInfoTask(blFamilyId);
            if (blFamilyAllInfo == null || blFamilyAllInfo.getFamilyInfo() == null) {
                return;
            }
            String familyVersion = blFamilyAllInfo.getFamilyInfo().getFamilyVersion();
            BLBaseResult blBaseResult = BLFamily.removeDeviceFromFamily(blDid, blFamilyId, familyVersion);
            showBLResultLog(blBaseResult, "删除单个设备");
        });
    }

    public void delBLFamily(Family family) {

        if (family == null || TextUtils.isEmpty(family.getBlFamilyId()) || family.getType() == 0) {
            return;
        }
        if (family.getType() != 1) {
            return;
        }
        if (!checkAppState()) {
            return;
        }
        String blFamilyId = family.getBlFamilyId();
        String name = family.getName();
        MyThreadManager.getInstance().doTask(() -> {
            BLFamilyAllInfo blFamilyAllInfo = queryBLFamilyAllInfoTask(blFamilyId);
            if (blFamilyAllInfo == null || blFamilyAllInfo.getFamilyInfo() == null) {
                return;
            }
            String familyVersion = blFamilyAllInfo.getFamilyInfo().getFamilyVersion();
            BLBaseResult blBaseResult = BLFamily.delFamily(blFamilyId, familyVersion);
            showBLResultLog(blBaseResult, "删除家庭-" + name);
        });
    }

    public void withActivity(Activity activity) {
        mActivity = activity;
    }

    public void addSdkDevices(List<BLDeviceInfo> blDeviceInfos) {
        for (BLDeviceInfo blDeviceInfo : blDeviceInfos) {
//            BLDNADevice bldnaDevice = BLModelUtil.toDNADevice(blDeviceInfo);
            addSdkDevice(blDeviceInfo);
        }
    }

    public void setBLFamilyListener(BLFamilyListener BLFamilyListener) {
        mBLFamilyListener = BLFamilyListener;
    }


    /*** 更新云端的家庭名称 */
    public void delBLDevice(BLDeviceInfo blDeviceInfo) {
        if (!checkAppState()) {
            return;
        }
        if (blDeviceInfo == null || isEmptyStr(blDeviceInfo.getDid()) || isEmptyStr(blDeviceInfo.getFamilyId())) {
            return;
        }
        String did = blDeviceInfo.getDid();
        String familyId = blDeviceInfo.getFamilyId();
        Family family = new FamilyDao(mContext).getById(familyId);
        if (family == null || isEmptyStr(family.getBlFamilyId())) {
            return;
        }
        MyThreadManager.getInstance().doTask(() -> {
            String blFamilyId = family.getBlFamilyId();
            delBLDeviceTask(did, blFamilyId);
        });
    }

    private void delBLDeviceTask(String did, String blFamilyId) {
        BLFamilyAllInfo blFamilyAllInfo = queryBLFamilyAllInfoTask(blFamilyId);
        if (blFamilyAllInfo == null || blFamilyAllInfo.getFamilyInfo() == null) {
            return;
        }
        BLFamilyInfo familyInfo = blFamilyAllInfo.getFamilyInfo();
        BLBaseResult blBaseResult = BLFamily.removeDeviceFromFamily(did, familyInfo.getFamilyId(), familyInfo.getFamilyVersion());
        showBLResultLog(blBaseResult, "delBLDevice:");
    }

    public boolean isEmptyStr(String str) {
        return TextUtils.isEmpty(str);
    }

    /*** 更新云端的家庭名称 */
    public void updateBLFamilyName(Family currFamily) {
        if (currFamily == null || currFamily.getType() != 1 || TextUtils.isEmpty(currFamily.getBlFamilyId())) {
            return;
        }
        if (!checkAppState()) {
            return;
        }
        MyThreadManager.getInstance().doTask(() -> {
            String blFamilyId = currFamily.getBlFamilyId();
            String name = currFamily.getName();
            BLFamilyAllInfo blFamilyAllInfo = queryBLFamilyAllInfoTask(blFamilyId);
            if (blFamilyAllInfo == null || blFamilyAllInfo.getFamilyInfo() == null) {
                return;
            }
            BLFamilyInfo familyInfo = blFamilyAllInfo.getFamilyInfo();
            familyInfo.setFamilyName(name);
            BLFamilyInfoResult familyInfoResult = BLFamily.modifyFamilyInfo(familyInfo);
            showBLResultLog(familyInfoResult, "更新家庭名称：" + name);
        });
    }


    private static class Holder {
        public static BLLocalFamilyManager INSTANCE = new BLLocalFamilyManager();
    }

    public void initContext(Context context) {
        if (mContext == null) {
            mContext = context;
        }
    }


    public void setBLFamilyId(String blFamilyId) {
        mBLFamilyId = blFamilyId;
        if (TextUtils.isEmpty(blFamilyId)) {
            return;
        }
//        Log.i(TAG, "setBLFamilyId: 查询BL家庭信息");
        // 家庭选择之后，设置家庭ID到SDK，便于后续SDK数据处理
        BLFamily.setCurrentFamilyId(blFamilyId);
//        queryFamilyAllInfo(blFamilyId);
    }


    /*** 更新获取家庭详细信息 */
    public void queryFamilyAllInfo(String familyId) {
        if (familyId == null)
            familyId = mBLFamilyId;
        if (TextUtils.isEmpty(familyId)) {
            return;
        }
        String[] familyIds = {familyId};
        MyThreadManager.getInstance().doTask(() -> {
            BLAllFamilyInfoResult infoResult = BLFamily.queryAllFamilyInfos(familyIds);
            if (infoResult != null && infoResult.succeed()) {
                if (infoResult.getAllInfos().size() > 0) {
                    BLFamilyAllInfo allInfo = infoResult.getAllInfos().get(0);
                    setCurrentFamilyAllInfo(allInfo);
                }
            }
        });
    }

    public boolean checkAppState() {
        if (!BLCommonUtils.checkNetwork(mContext)) {
            toast("网络不可用!");
            Log.e(TAG, "checkAppState:网络不可用 ");
            return false;
        }
        if (!isLogin) {
            toast("没有登录!");
            Log.e(TAG, "checkAppState:没有登录 ");
            return false;
        }
        return true;
    }

    /*** 创建单个网关设备 */
    public void createOneBlDevice(final Family family, DeviceCategory deviceCategory) {
        if (!checkAppState()) {
            return;
        }
        if (family == null || TextUtils.isEmpty(family.getBlFamilyId())) {
            toast("当前家庭还没有绑定网关");
            return;
        }
        if (!TextUtils.isEmpty(deviceCategory.getBlDid())) {
            toast("当前设备已经是网关设备");
            return;
        }

        getFamilyLocalDevice(family.getFamilyId());
        if (mLocalDnaDevice == null) {
            return;
        }
        showLoading("正在创建网关设备");
        MyThreadManager.getInstance().doTask(() -> {
            String blFamilyId = family.getBlFamilyId();
            BLFamilyAllInfo familyAllInfo = queryBLFamilyAllInfoTask(blFamilyId);
            if (familyAllInfo == null) {
                dismissLoading();
                return;
            }
            BLFamilyInfo familyInfo = familyAllInfo.getFamilyInfo();
            if (familyInfo == null) {
                dismissLoading();
                handlerToast("没有找到对应的网关家庭");
                return;
            }
            String familyId = family.getFamilyId();
            DeviceCategoryDao categoryDao = new DeviceCategoryDao(mContext);
            createBLFamilyDevice(familyInfo, mLocalDnaDevice, familyId, categoryDao, deviceCategory, "01");
            dismissLoading();
        });

    }

    public BLFamilyAllInfo queryBLFamilyAllInfoTask(String blFamilyId) {
        String[] blFamilyIds = {blFamilyId};
        BLAllFamilyInfoResult allFamilyInfos = BLFamily.queryAllFamilyInfos(blFamilyIds);
        if (allFamilyInfos == null || !allFamilyInfos.succeed() || allFamilyInfos.getAllInfos().size() < 1) {
            return null;
        }
        BLFamilyAllInfo familyAllInfo = allFamilyInfos.getAllInfos().get(0);
        return familyAllInfo;
    }


    public void setCurrentFamilyAllInfo(BLFamilyAllInfo allInfo) {
        if (allInfo == null) {
            return;
        }
        currentFamilyAllInfo = allInfo;
        mBLFamilyInfo = allInfo.getFamilyInfo();
        setCurrentFamilyVersion(currentFamilyAllInfo.getFamilyInfo().getFamilyVersion());
    }

    private void setCurrentFamilyVersion(String familyVersion) {
        currentFamilyVersion = familyVersion;
    }


    public void delLocalDevice(BLDNADevice device) {
        BLDeviceInfoDao dao = new BLDeviceInfoDao(mContext);
        BLDeviceInfo blDeviceInfo = new BLDeviceInfo(device);
        dao.delete(blDeviceInfo);
    }

    /*** 检查家庭名称是否可用 */
    public boolean checkBLFamilyName(String familyName) {
        if (TextUtils.isEmpty(familyName)) {
            return false;
        }
        if (mAllBLFamilyInfoList == null || mAllBLFamilyInfoList.size() < 1) {
            return true;
        }
        for (BLFamilyBaseInfo info : mAllBLFamilyInfoList) {
            String blFamilyName = info.getFamilyInfo().getFamilyName();
            if (familyName.equals(blFamilyName)) {
                return false;
            }
        }
        return true;
    }

    /*** 后台登录操作 */
    public void login() {
        boolean network = BLCommonUtils.checkNetwork(mContext);
        if (!network) {
            Log.e(TAG, "login: 失败：网络错误！");
        }
        String[] accountInfo = StorageHelper.getBLAccountInfo();
        if (accountInfo != null && accountInfo.length == 2) {
            final String userName = accountInfo[0];
            final String userPassword = accountInfo[1];
            MyThreadManager.getInstance().doTask(() -> {
                BLLoginResult loginResult = BLAccount.login(userName, userPassword);
                if (loginResult != null && loginResult.getError() == BLAppSdkErrCode.SUCCESS) {
                    //存储登陆成功信息
                    saveBLUserInfo(loginResult);
                    isLogin = true;
                    updateShareFamilysBLInfo();
                }
                showBLResultLog(loginResult, "后台登录操作");
            });
        }
    }


    /*** 子线程执行添加网关家庭操作 */
    public void createNewBLFamilyTask() {
        Log.i(TAG, "CreateBLFamilyTask: ");
        String newFamilyName = mFamily.getName();
        //检查名称是否可用，防止同名
        BLFamilyBaseInfoListResult userFamilyResults = BLFamily.queryLoginUserFamilyBaseInfoList();
        boolean nameIsOk = checkNewBLFamilyName(newFamilyName, userFamilyResults);
        if (!nameIsOk) {
            handlerToast("已经有同名的网关家庭了!");
            dismissLoading();
            return;
        }
        BLFamilyInfoResult result = BLFamily.createDefaultFamily(newFamilyName, null, null, null);
        if (result == null || !result.succeed() || result.getFamilyInfo() == null) {
            handlerToast("创建网关家庭失败！");
            dismissLoading();
            return;
        }
        mBLFamilyInfo = result.getFamilyInfo();
        mBLFamilyId = mBLFamilyInfo.getFamilyId();
        mFamilyId = mFamily.getFamilyId();
        FamilyDao familyDao = new FamilyDao(mContext);
        mFamily.setBlFamilyId(mBLFamilyInfo.getFamilyId());
        mFamily.setBlType(1);
        familyDao.updateFamily(mFamily);
        addModuleDevicesTask(mBLFamilyInfo);
    }

    /*** 检查名称是否可用，防止同名 */
    private boolean checkNewBLFamilyName(String newfamilyName, BLFamilyBaseInfoListResult userFamilyResults) {
        if (userFamilyResults == null && !userFamilyResults.succeed()) {
            Log.e(TAG, "createNewBLFamilyTask: 查询登录用户信息失败");
            handlerToast("查询用户信息失败,无法绑定家庭");
            return false;
        }
        List<BLFamilyBaseInfo> baseInfos = userFamilyResults.getInfoList();
        if (baseInfos != null && baseInfos.size() > 0) {
            for (BLFamilyBaseInfo baseInfo : baseInfos) {
                BLFamilyInfo familyInfo = baseInfo.getFamilyInfo();
                String familyName = familyInfo.getFamilyName();
                String familyId = familyInfo.getFamilyId();
//                Log.i(TAG, "familyInfo: familyName = " + familyName + "  familyId = " + familyId);
                if (newfamilyName.equals(familyName)) {
                    handlerToast("云端已有同名家庭，请修改再试：" + familyName);
                    return false;
                }
            }
        }
        return true;
    }

    /*** 保存登陆后用户的信息 **/
    public void saveBLUserInfo(BLLoginResult loginResult) {
        if (loginResult == null || !loginResult.succeed()) {
            return;
        }
        BaseApp.getmBLUserInfoUnits().login(
                loginResult.getUserid(),
                loginResult.getLoginsession(),
                loginResult.getNickname(),
                loginResult.getIconpath(),
                loginResult.getLoginip(),
                loginResult.getLogintime(),
                loginResult.getSex(),
                null,
                loginResult.getPhone(),
                loginResult.getEmail(),
                loginResult.getBirthday());
    }

    /*** 创建网关家庭*/
    public void createBLFamily(Family family) {
        mFamily = family;
        if (family == null || mLocalDnaDevice == null) {
            Log.i(TAG, "createBLFamily: family == null || mLocalDnaDevice==null");
            dismissLoading();
            return;
        }
        mFamilyId = family.getFamilyId();
        DeviceCategoryDao categoryDao = new DeviceCategoryDao(mContext);
        List<DeviceCategory> categorys = categoryDao.getFamilyDeviceCategorys(mFamily.getFamilyId());
        mFamilyCategorys = categorys;
        createNewBLFamilyTask();
    }


    /*** 创建当前家庭的所有BL设备 */
    public BLModuleControlResult addModuleDevicesTask(BLFamilyInfo blFamilyInfo) {
        BLDNADevice bldnaDevice = mLocalDnaDevice;
        if (bldnaDevice == null) {
            dismissLoading();
            return null;
        }
        String familyId = mFamilyId;
        Log.i(TAG, "bldnaDevice =  " + bldnaDevice.toJSONString());
        String blFamilyId = blFamilyInfo.getFamilyId();
        BLDeviceInfo gatewayDeviceInfo = BLModelUtil.toBLDeviceInfo(bldnaDevice);
        gatewayDeviceInfo.setBlType(0);
        gatewayDeviceInfo.setFamilyId(familyId);
        updateBLDeviceInfo(gatewayDeviceInfo);
        Log.i(TAG, "addModuleDevicesTask: gatewayDeviceInfo= " + gatewayDeviceInfo.toString());
        BLDeviceInfo blDeviceInfo = new BLDeviceInfoDao(mContext).getByUuid(gatewayDeviceInfo.getDid());
        Log.e(TAG, "update gatewayDeviceInfo : "+blDeviceInfo.toString());


        DeviceCategory allDeviceCategory = new DeviceCategory();
        allDeviceCategory.setName("所有灯");
        allDeviceCategory.setGroupId("00");
        //创建单个的全部设备
        createBLFamilyAllDevice(blFamilyInfo, bldnaDevice, familyId, allDeviceCategory, "01");
        DeviceCategoryDao deviceDao = new DeviceCategoryDao(mContext);
        if (mFamilyCategorys == null || mFamilyCategorys.size() < 1) {
            handlerToast("添加网关家庭成功");
            dismissLoading();
            return null;
        }
        for (DeviceCategory deviceCategory : mFamilyCategorys) {
            String roomId = "01";
            createBLFamilyDevice(blFamilyInfo, bldnaDevice, familyId, deviceDao, deviceCategory, roomId);
        }
        handlerToast("添加网关设备成功");
        dismissLoading();
        if (mBLFamilyListener != null) {
            mHandler.post(() -> {
                mBLFamilyListener.notifyBlFamilyResult(true, 0, "");
            });
        }
        return null;
    }

    /***创建单个网关家庭设备-全部*/
    private void createBLFamilyAllDevice(BLFamilyInfo blFamilyInfo, BLDNADevice bldnaDevice, String familyId, DeviceCategory deviceCategory, String roomId) {
        String name = deviceCategory.getName();
        String blFamilyId = blFamilyInfo.getFamilyId();
        //家庭设备
        BLFamilyDeviceInfo deviceInfo = createBLFamilyDeviceInfo(deviceCategory, blFamilyId, roomId, bldnaDevice);
        //家庭模块
        BLFamilyModuleInfo blFamilyModuleInfo = createBLFamilyModuleInfo(blFamilyId, roomId, name, bldnaDevice.getDid());
        BLModuleControlResult result = BLFamily.addModuleToFamily(blFamilyModuleInfo,
                blFamilyInfo, deviceInfo, null);
        String flag = "createBLFamilyDevice";
        showBLResultLog(result, flag);
        if (result != null && result.succeed()) {
            deviceCategory.setBlDid(deviceInfo.getDid());
            BLDNADevice dnaDevice = familyDeviceToDnaDevice(deviceInfo);
            BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(deviceInfo);
            blDeviceInfo.setFamilyId(familyId);
            updateBLDeviceInfo(blDeviceInfo);
            AppManager.getInstance(mContext).mBLAllDeviceInfo = blDeviceInfo;
            addSdkDevice(dnaDevice);
        }
    }

    /***创建单个网关家庭设备*/
    private void createBLFamilyDevice(BLFamilyInfo blFamilyInfo, BLDNADevice bldnaDevice, String familyId, DeviceCategoryDao deviceDao, DeviceCategory deviceCategory, String roomId) {
        String name = deviceCategory.getName();
        String groupId = deviceCategory.getGroupId();
        String blFamilyId = blFamilyInfo.getFamilyId();
        //家庭设备
        BLFamilyDeviceInfo deviceInfo = createBLFamilyDeviceInfo(deviceCategory, blFamilyId, roomId, bldnaDevice);
        //家庭模块
        BLFamilyModuleInfo blFamilyModuleInfo = createBLFamilyModuleInfo(blFamilyId, roomId, name, bldnaDevice.getDid());
        BLModuleControlResult result = BLFamily.addModuleToFamily(blFamilyModuleInfo,
                blFamilyInfo, deviceInfo, null);
        String flag = "createBLFamilyDevice";
        showBLResultLog(result, flag);
        if (result != null && result.succeed()) {
            deviceCategory.setBlDid(deviceInfo.getDid());
            deviceDao.updateDeviceCategory(deviceCategory);
            BLDNADevice dnaDevice = familyDeviceToDnaDevice(deviceInfo);
            BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(deviceInfo);
            blDeviceInfo.setFamilyId(familyId);
            updateBLDeviceInfo(blDeviceInfo);
            addSdkDevice(dnaDevice);
        }
    }

    /*** 显示BLResult log */
    public void showBLResultLog(BLBaseResult result, String flag) {
        if (result != null) {
            Log.i(TAG, flag + ": succeed = " + result.succeed() + "  error = " + result.getError() + "  msg = " + result.getMsg());
        }
    }

    /*** 创建BL家庭模块 */
    @NonNull
    private BLFamilyModuleInfo createBLFamilyModuleInfo(String familyId, String roomId, String name, String moduleDeviceId) {
        //创建家庭模块
        BLFamilyModuleInfo blFamilyModuleInfo = new BLFamilyModuleInfo();
        blFamilyModuleInfo.setFamilyId(familyId);
        blFamilyModuleInfo.setRoomId(roomId);
        blFamilyModuleInfo.setName(name);
        blFamilyModuleInfo.setModuleType(1);    // 模块类型 SP
//          blFamilyModuleInfo.setModuleType(3);
        blFamilyModuleInfo.setFlag(0);
        blFamilyModuleInfo.setOrder(1);
        blFamilyModuleInfo.setFollowDev(1);     // 模块下挂载设备数 1

        //模块设备
        BLFamilyModuleInfo.ModuleDeviceInfo moduleDeviceInfo = new BLFamilyModuleInfo.ModuleDeviceInfo();
        moduleDeviceInfo.setDid(moduleDeviceId);
        moduleDeviceInfo.setSdid(null);
        moduleDeviceInfo.setOrder(1);
        moduleDeviceInfo.setContent(null);

        //挂载子设备
        List<BLFamilyModuleInfo.ModuleDeviceInfo> moduleDevices = new ArrayList<>();
        moduleDevices.add(moduleDeviceInfo);
        blFamilyModuleInfo.setModuleDevs(moduleDevices);
        return blFamilyModuleInfo;
    }

    public void handlerToast(final String msg) {
        mHandler.post(() -> toast(msg));
    }

    public void toast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }


    /*** 创建BL家庭设备 */
    public BLFamilyDeviceInfo createBLFamilyDeviceInfo(DeviceCategory deviceCategory, String blFamilyId, String roomId, BLDNADevice bldnaDevice) {
        BLFamilyDeviceInfo deviceInfo = BLModelUtil.toFamilyDeviceInfo(bldnaDevice);
        deviceInfo.setName(deviceCategory.getName());
        deviceInfo.setFamilyId(blFamilyId);
        deviceInfo.setRoomId(roomId);
        String mac = bldnaDevice.getMac().replace(":", "");
        String did = mac + "0000" + "9b500000" + "0001" + "00" + deviceCategory.getGroupId();
        String pid = "0000000000000000000000009b500000";
        deviceInfo.setDid(did);
        deviceInfo.setPid(pid);
        return deviceInfo;
    }

    public BLDNADevice familyDeviceToDnaDevice(BLFamilyDeviceInfo deviceInfo) {
        BLDNADevice bldnaDevice = new BLDNADevice();
//        deviceInfo.setBLFamilyId(familyId);
//        deviceInfo.setRoomId(roomId);
        bldnaDevice.setDid(deviceInfo.getDid());
        bldnaDevice.setPid(deviceInfo.getPid());
        bldnaDevice.setMac(deviceInfo.getMac());
        bldnaDevice.setName(deviceInfo.getName());
        bldnaDevice.setPassword(deviceInfo.getPassword());
        bldnaDevice.setType(deviceInfo.getType());
        bldnaDevice.setLock(false);
        bldnaDevice.setKey(deviceInfo.getAeskey());
        bldnaDevice.setId(deviceInfo.getTerminalId());
        bldnaDevice.setExtend(deviceInfo.getExtend());
        return bldnaDevice;
    }
}

